//
//  SelectClientViewController.m
//  Marketing
//
//  Created by wmm on 16/3/6.
//  Copyright © 2016年 Hanen 3G 01. All rights reserved.
//

#import "SelectClientViewController.h"
#import "MJRefresh.h"

@interface SelectClientViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
    NSMutableArray *_searchArray;
    UIView  *_backView;
    BOOL  isSearch;
    NSString *_name;
    int rows;
    
    BOOL isMore;
}
@property(nonatomic)       int customerCount;
@property(nonatomic,strong)NSMutableArray   *customerList;

@property(nonatomic,strong)NSMutableArray *companyList;
@property(nonatomic,strong)NSMutableArray *idList;
@property(nonatomic,strong)NSMutableArray *cnameList;
@property(nonatomic,strong)NSMutableArray *addressList;

//@property (strong, nonatomic) UISearchBar * searchBar;
@property(nonatomic,strong)UITableView         *clientTableView;
@property(nonatomic,strong) UISearchBar *searchBar;

@end

@implementation SelectClientViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    isSearch = NO;
    rows = 20;
    self.view.backgroundColor =[UIColor whiteColor];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.titleView = [ViewTool getNavigitionTitleLabel:@"公司名称"];
    self.navigationItem.leftBarButtonItem=[ViewTool getBarButtonItemWithTarget:self WithAction:@selector(goToBack)];
    _searchArray = [NSMutableArray array];
    _companyList = [NSMutableArray array];
    //    _idList = [NSMutableArray array];
    //    _cnameList = [NSMutableArray array];
    //    _addressList = [NSMutableArray array];
    
    [self addSearchBar];
    [self reloadData];
    
}
-(void)addSearchBar{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCreenW, 44)];
    view.backgroundColor  = graySectionColor;
    [self.view addSubview:view];
    
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, KSCreenW , 44)];
    [_searchBar setBackgroundImage:[ViewTool getImageFromColor:graySectionColor WithRect:_searchBar.frame]];
    //    _searchBar.showsCancelButton = YES;
    _searchBar.placeholder =@"搜索";
    //    for (UIView *view in [_searchBar.subviews[0] subviews]) {
    //        if ([view isKindOfClass:[UIButton class]]) {
    //            UIButton *btn = (UIButton *)view;
    //            [btn setTitle:@"取消" forState:UIControlStateNormal];
    //            [btn setTitleColor:grayFontColor forState:UIControlStateNormal];
    //            btn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    //        }
    //    }
    _searchBar.delegate = self;
    [view addSubview:_searchBar];
    
    //    self.tableView.tableHeaderView = _searchBar;
    //    CGRect searchBarRect2=CGRectMake(0, 0, _alphaView.width, 44);
    //    _searchBar2=[[UISearchBar alloc]initWithFrame:searchBarRect2];
    //    _searchBar2.placeholder=@"搜索";
    //    _searchBar2.showsCancelButton=YES;//显示取消按钮
    //    //添加搜索框到页眉位置
    //    _searchBar2.delegate=self;
    //
    //    self.staffTableView.tableHeaderView = _searchBar2;
}
- (void)handleTap:(UIGestureRecognizer *)tap
{
    UIView *view = tap.view;
    [view removeFromSuperview];
    [_searchBar resignFirstResponder];
    [_searchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    isSearch = NO;
    [_searchArray removeAllObjects];
    [_clientTableView reloadData];
    
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    
    //    NSArray * companyArray = [_customerList objectForKey:@"company"];
    
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    [_backView removeFromSuperview];
    
    [_searchArray removeAllObjects];
    if(searchText != nil){
        isSearch = YES;
    }
    for (int i = 0; i < _companyList.count; i++) {
        //        NSLog(@"%@",_companyList[i]);
        NSString *companyStr = _companyList[i];
        NSRange rang = [companyStr rangeOfString:searchText];
        if (rang.length != 0) {
            [_searchArray addObject:_companyList[i]];
            [_clientTableView reloadData];
        }
    }
    if ([searchText isEqualToString: @""]) {
        [_searchArray removeAllObjects];
        isSearch = NO;
        [_clientTableView reloadData];
        _backView = [[UIView alloc] initWithFrame:CGRectMake(0, searchBar.maxY + 64, KSCreenW, KSCreenH - searchBar.maxY - 64)];
        _backView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:_backView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
        [_backView addGestureRecognizer:tap];
        [_backView addGestureRecognizer:pan];
    }
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [_searchArray removeAllObjects];
    isSearch = YES;
    //    NSArray * companyArray = [_customerList objectForKey:@"company"];
    for (int i = 0; i < _companyList.count; i++) {
        NSLog(@"%@",_companyList[i]);
        NSString *companyStr = _companyList[i];
        NSRange rang = [companyStr rangeOfString:searchBar.text];
        if (rang.length != 0) {
            [_searchArray addObject:_companyList[i]];
            [_clientTableView reloadData];
        }
    }
    [_searchBar resignFirstResponder];
}
- (void)viewWillAppear:(BOOL)animated
{
    isMore = NO;
    self.tabBarController.hidesBottomBarWhenPushed = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.hidesBottomBarWhenPushed = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_searchBar resignFirstResponder];
}
- (void)reloadnewdata
{
    isMore = NO;
    rows = 20;
    isSearch = NO;
    [_customerList removeAllObjects];
    [_searchArray removeAllObjects];
    [self reloadData];
}

- (void)reloadmoredata
{
    isMore = YES;
    rows = rows + 20;
    [self reloadData];
    
}

- (void)reloadData{
    
    //    self.delegate = self.navigationController;
    NSNumber *sortNum = [NSNumber numberWithInt:3];
    NSNumber *sortwayNum = [NSNumber numberWithInt:2];
    NSNumber *pagesNum = [NSNumber numberWithInt:1];
    NSNumber *rowsNum = [NSNumber numberWithInt:rows];
    NSDictionary * dic =@{@"token":TOKEN,@"uid":@(UID),@"sort":sortNum,@"sortWay":sortwayNum,@"pages":pagesNum,@"rows":rowsNum,};
    [DataTool sendGetWithUrl:MY_CLIENT_URL parameters:dic success:^(id data) {
        
        //        int code = [[(NSDictionary *)data objectForKey:@"code"] intValue];
        //        if(code != 100)//连接500和501
        //        {
        //            NSString * message = [(NSDictionary *)data objectForKey:@"message"];
        //            [self.view makeToast:message];
        //        }else{
        //
        //        }
        
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        _customerCount = [[(NSDictionary *)jsonDic objectForKey:@"customerCount"] intValue];
        _customerList = [(NSDictionary *)jsonDic objectForKey:@"customerList"];
        NSLog(@"%@-----",jsonDic);
        [self setCompanyName];
        
        if (isMore == YES) {
            [_clientTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows-20 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
        }

        [_clientTableView.mj_header endRefreshing];
        if (_customerCount == _customerList.count) {
            [_clientTableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [_clientTableView.mj_footer endRefreshing];
        }
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)setCompanyName{
    [_companyList removeAllObjects];
    
    //    NSMutableDictionary * mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:_customerCount];
    for (NSMutableDictionary *client in _customerList) {
        NSLog(@"client:%@",client);
        NSLog(@"%@",[client objectForKey:@"id"]);
        [_idList addObject:[client objectForKey:@"id"]];
        [_companyList addObject:[client objectForKey:@"company"]];
        [_cnameList addObject:[client objectForKey:@"cname"] ];
        [_addressList addObject:[client objectForKey:@"address"] ];
//        NSLog(@"%@",_cnameList);
    }
    [self addClientTable];
}

//我的客户详情
- (void)initData:(int)clientId{
    
    NSDictionary * dic =@{@"token":TOKEN,@"uid":@(UID),@"cid":@([[_customerList[clientId] objectForKey:@"id"] intValue]) };
    [DataTool postWithUrl:DETAIL_CLIENT_URL parameters:dic success:^(id data) {
        NSDictionary *jsonDic = [DataTool changeType:[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]];
        NSLog(@"jsonDic%@",jsonDic);
//        int code = [[jsonDic objectForKey:@"code"] intValue];
//        if(code == 100)
//        {
//            NSString * message = [jsonDic objectForKey:@"message"];
//            [self.view makeToast:message];
//        }else{
        id json = [DataTool changeType:jsonDic];
        NSArray *clientArray = json[@"contactsList"];
        NSDictionary *dic = [NSDictionary dictionary];
        NSMutableArray *nameArr = [[NSMutableArray alloc] init];
        NSMutableArray *idArr = [[NSMutableArray alloc] init];

        NSString *visitid = [NSString string];
        NSString *vid = [NSString string];
        
        if (clientArray.count != 0) {
            for (int i = 0; i < clientArray.count ; i ++) {
                dic = [clientArray objectAtIndex:i];
                NSString *name = [DataTool changeType:[dic objectForKey:@"name"]];
                [nameArr addObject:name];
                vid = [DataTool changeType:[dic objectForKey:@"id"]];
                [idArr addObject:vid];
            }
                visitid = [DataTool changeType:[dic objectForKey:@"cid"]];
        }
        NSLog(@"公司名称 - %@++++ %@  %@++",clientArray,idArr,visitid);
        [self.delegate selectClient:idArr withName:[_customerList[clientId] objectForKey:@"company"] withCname:nameArr withAddress:[_customerList[clientId] objectForKey:@"address"] vid:visitid];
//            [self performSelector:@selector(goToBack) withObject:nil afterDelay:1.0f];
               [self goToBack];
//        }
    } fail:^(NSError *error) {
        [self.view makeToast:error.localizedDescription];
    }];
    
}

- (void)addClientTable{
    //    NSLog(@"%f-----%f",self.view.width,self.view.height);
    _clientTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 44, self.view.width, self.view.height-44)];
    _clientTableView.delegate = self;
    _clientTableView.dataSource = self;
    _clientTableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.view addSubview:_clientTableView];
    
    _clientTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self reloadnewdata];
    }];
    _clientTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self reloadmoredata];
    }];
    
    [self addSearchBar];
}

- (void)goToBack{
    [self.navigationController popViewControllerAnimated:NO];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (isSearch) {
        return _searchArray.count;
    }else{
        return _companyList.count;
        
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    cell.textLabel.textColor = blackFontColor;
    cell.textLabel.font = [UIFont systemFontOfSize:14.0f] ;
    if (isSearch) {
        cell.textLabel.text = _searchArray[indexPath.row];
    }else{
        cell.textLabel.text = [_customerList[indexPath.row] objectForKey:@"company"];
        
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self initData:(int)indexPath.row];
    
 
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_searchBar resignFirstResponder];
}

@end
